#include "../include/Acceptor.hpp"
#include "../include/Mylogger.hpp"

namespace cdm{

Acceptor::Acceptor(uint16_t port,const string &ip)
:_addr(port,ip),
   _socket(){
}

void Acceptor::ready(){
    setReuseAddr(true);
    setReusePort(true);
    bind();
    listen();
}
int Acceptor::accept(){
    int fd = ::accept(_socket.fd(),NULL,NULL);
    if(fd < 0){
        perror("accept");
        LOG_ERROR("accopt failed");
    }
    return fd;
}
void Acceptor::setReuseAddr(bool set){
    int on = set ? 1:0;
    int ret = setsockopt(_socket.fd(),SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on));
    if(ret < 0){
        perror("setsockopt");
        LOG_ERROR("setReuseAddr failed");
    }
}

void Acceptor::setReusePort(bool set){
    int on = set ? 1:0;
    int ret = setsockopt(_socket.fd(),SOL_SOCKET,SO_REUSEPORT,&on,sizeof(on));
    if(ret < 0){
        perror("setsockopt");
        LOG_ERROR("setReusePort failed");
    }
}

int Acceptor::fd(){
    return _socket.fd();
}

void Acceptor::bind(){
    int ret = ::bind(_socket.fd(),(const struct sockaddr*)_addr.getAddressPtr(),sizeof(_addr));
    if(ret < 0){
        perror("bind");
        LOG_ERROR("bind failed");
    }
}
void Acceptor::listen(){
    int ret = ::listen(_socket.fd(),15000);
    if( ret < 0){
        perror("listen");
        LOG_ERROR("listen failed");
    }
}






}//end of namespace



